/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package libraryproject;

import database_objects.Author;
import database_objects.Book;
import database_objects.Department;
import database_objects.EditionBook;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JDialog;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import user_client.LibrarianUserClient;

/**
 *
 * @author pawel
 */
public class BooksManagementsPane extends javax.swing.JPanel {

    /**
     * Creates new form BooksManagementsPane
     */
    public BooksManagementsPane() {
        initComponents();

        authorsList.setModel(authorsListModel);
        model = (DefaultTableModel) resultTable.getModel();
        resultTable.getSelectionModel().addListSelectionListener(
                new MySelectionListener());

    }

    public BooksManagementsPane(LibrarianUserClient client) {
        initComponents();
        this.client = client;
        authorsListModel = new DefaultListModel();
        authorsList.setModel(authorsListModel);
        model = (DefaultTableModel) resultTable.getModel();
        resultTable.getSelectionModel().addListSelectionListener(
                new MySelectionListener());
    }

    public void setAuthors(ArrayList<Author> authors) {
        this.authors.clear();
        for (Author author : authors) {
            System.out.println(author.toString());
            authorsListModel.addElement(author);
            this.authors.add(author);
        }
        System.out.println("aktualizacja");
    }

    public void setEdition(EditionBook edition, Department department) {
        isbnField.setText(edition.getIsbn());
        titleField.setText(edition.getTitle());
        editionField.setText(edition.getNameOfEditionHouse());
        dateField.setText(edition.getDateOfPublishing());
        setDepartment(department);
        if (authorsListModel.toArray().length > 0) {
            jPanel4.setEnabled(false);
        } else {
            jPanel4.setEnabled(true);
        }
        currentEdition = edition;
    }

    public void setDepartment(Department department) {
        this.caseNumberField.setText(department.getBookCaseNumber());
        this.departmentNameField.setText(department.getName());
        this.currentDepartment = department;
    }

    public void setBook(EditionBook edition, Department department, ArrayList<Author> authors) {
        
        System.out.println(authors.size());
        System.out.println("-------------------------");
        currentBook = new Book(department, authors, edition);
        System.out.println(department.toString());
        for (Author author : authors) {
            System.out.println(author.toString());
        }

        System.out.println(edition.toString());

        isbnField.setText(edition.getIsbn());
        titleField.setText(edition.getTitle());
        editionField.setText(edition.getNameOfEditionHouse());
        dateField.setText(edition.getDateOfPublishing());
        System.out.println(edition.getDateOfPublishing());
        setDepartment(department);
        if (authorsListModel.toArray().length > 0) {
            jPanel4.setEnabled(false);
        } else {
            jPanel4.setEnabled(true);
        }
        currentEdition = edition;
        this.authors.clear();
        for (Author author : authors) {
            System.out.println(author.toString());
            authorsListModel.addElement(author);
            this.authors.add(author);
        }
        System.out.println("aktualizacja");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        resultTable = new javax.swing.JTable();
        jPanel5 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        isbnField = new javax.swing.JFormattedTextField();
        jLabel2 = new javax.swing.JLabel();
        editionField = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        dateField = new javax.swing.JFormattedTextField();
        jLabel4 = new javax.swing.JLabel();
        titleField = new javax.swing.JTextField();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        authorsList = new javax.swing.JList();
        jPanel2 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        departmentNameField = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        caseNumberField = new javax.swing.JTextField();
        choseEditionButton = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        searchButton = new javax.swing.JButton();
        jLabel8 = new javax.swing.JLabel();
        resultLabel = new javax.swing.JLabel();
        position = new javax.swing.JSpinner();
        jLabel7 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        idOfBook = new javax.swing.JLabel();

        setPreferredSize(new java.awt.Dimension(500, 363));
        setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        resultTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "id książki", "isbn", "tytuł", "wydawnictwo", "wypożyczona"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Boolean.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(resultTable);

        add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 490, 140));

        jPanel5.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("wydanie"));
        jPanel3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setText("isbn:");
        jPanel3.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(6, 21, 148, 26));

        isbnField.setEnabled(false);
        jPanel3.add(isbnField, new org.netbeans.lib.awtextra.AbsoluteConstraints(6, 49, 148, 26));

        jLabel2.setText("wydawnictwo:");
        jPanel3.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(6, 77, 148, 26));

        editionField.setEnabled(false);
        editionField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editionFieldActionPerformed(evt);
            }
        });
        jPanel3.add(editionField, new org.netbeans.lib.awtextra.AbsoluteConstraints(6, 105, 148, 26));

        jLabel3.setText("data wydania:");
        jPanel3.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(6, 133, 148, 26));

        dateField.setEnabled(false);
        jPanel3.add(dateField, new org.netbeans.lib.awtextra.AbsoluteConstraints(6, 161, 148, 26));

        jLabel4.setText("tytuł:");
        jPanel3.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(6, 189, 148, 26));

        titleField.setEnabled(false);
        jPanel3.add(titleField, new org.netbeans.lib.awtextra.AbsoluteConstraints(6, 217, 148, 26));

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Autorzy:"));
        jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        authorsList.setEnabled(false);
        jScrollPane2.setViewportView(authorsList);

        jPanel4.add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(6, 19, 140, 70));

        jPanel3.add(jPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 10, 160, 100));

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("wybierz dział"));
        jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel5.setText("nazwa:");
        jPanel2.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 20, 100, 26));

        departmentNameField.setEnabled(false);
        jPanel2.add(departmentNameField, new org.netbeans.lib.awtextra.AbsoluteConstraints(6, 49, 150, 26));

        jLabel6.setText("numer regału:");
        jPanel2.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(6, 77, 110, 26));

        caseNumberField.setEnabled(false);
        jPanel2.add(caseNumberField, new org.netbeans.lib.awtextra.AbsoluteConstraints(6, 105, 150, 26));

        jPanel3.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 110, 160, 140));

        choseEditionButton.setText("wybierz wydanie");
        choseEditionButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                choseEditionButtonActionPerformed(evt);
            }
        });
        jPanel3.add(choseEditionButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 210, 140, 30));

        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jButton4.setText("dodaj książkę");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 100, 140, 30));

        jButton5.setText("usuń książkę");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton5, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 130, 140, 30));

        searchButton.setText("szukaj");
        searchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButtonActionPerformed(evt);
            }
        });
        jPanel1.add(searchButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 160, 140, -1));
        jPanel1.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 138, -1, 6));
        jPanel1.add(resultLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(24, 331, -1, -1));

        position.setModel(new javax.swing.SpinnerNumberModel(0, 0, 100, 1));
        jPanel1.add(position, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 30, 136, -1));

        jLabel7.setText("pozycja na półce");
        jPanel1.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));

        jLabel9.setText("id książki:");
        jPanel1.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 60, -1, -1));

        idOfBook.setText("nie zaznaczono");
        jPanel1.add(idOfBook, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 80, -1, -1));

        jPanel3.add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 10, 160, 200));

        jPanel5.add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 490, -1));

        add(jPanel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 160, 500, 250));
    }// </editor-fold>//GEN-END:initComponents

    private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed

        try {


            ArrayList<Book> books = client.getBooksByEdition(isbnField.getText());

            while (model.getRowCount() > 0) {
                try {
                    model.removeRow(0);
                } catch (Exception a) {
                    System.out.println("ERRRORRRRRRRR????");
                }

            }

            
            for (Book book : books) {
                
                String[] val =
                        new String[5];
                val[0] = book.getIdOfBook();
                val[1] = book.getIsbn();
                val[2] = book.getTitle();
                val[3] = book.getNameOfEdition();
               
                model.addRow(val);
            }

            resultTable.revalidate();

            resultTable.repaint();

        } catch (SQLException e1) { // TODO Auto-generated catch block
            e1.printStackTrace();
        } // T
        // TODO add your handling code here:
    }//GEN-LAST:event_searchButtonActionPerformed

    private void choseEditionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_choseEditionButtonActionPerformed
        JDialog frame = new JDialog();
        currentEdition = new EditionBook(isbnField.getText(),
                editionField.getText(), dateField.getText(),
                titleField.getText(), null);
        EditionChoicePane edition = null;
        try {
            edition = new EditionChoicePane(
                    client, currentBook, this, frame, currentEdition, currentDepartment);
        } catch (ParseException ex) {
            Logger.getLogger(BooksManagementsPane.class.getName()).log(Level.SEVERE, null, ex);
        }
        frame.add(edition);
        frame.setVisible(true);
        frame.setSize(edition.getPreferredSize());
        // TODO add your handling code here:
    }//GEN-LAST:event_choseEditionButtonActionPerformed

    private void editionFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editionFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_editionFieldActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed

        /*
         * String departmentName = departmentNameField.getText(); String
         * departmentCaseNumber = caseNumberField.getText();
         *
         * String editionName = editionField.getText();
         */      /*
         * String editionDate = dateField.getText();
         *
         */
        String isbnString = isbnField.getText();
        Integer positionOfBookObj = (Integer) position.getValue();
        String positionOfBook = positionOfBookObj.toString();
        String title = titleField.getText();
        /*
         * Object[] authorsObj = this.authorsListModel.toArray();
         * this.authors.clear();
         *
         * for (Object obj : authorsObj) { this.authors.add((Author) obj);
        }
         */


        if ((isbnString.length() > 0)
                && (title.length() > 0) && (positionOfBook.length() > 0)) {


            try {


                Integer index = client.addBook(isbnString, positionOfBook);
                if (index != -1) {
                    String[] newRow = new String[5];
                    newRow[0] =
                            index.toString();
                    newRow[1] = isbnField.getText();
                    newRow[2] =
                            titleField.getText();
                    newRow[3] = editionField.getText(); //newRow[4]

                    model.addRow(newRow);
                    model.fireTableDataChanged();
                    resultTable.revalidate();
                    resultTable.repaint();

                    resultLabel.setText("Dodano element");
                } else {
                    resultLabel.setText("Podana książka już istnieje");
                }
            } catch (SQLException e1) { // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }


        // TODO add your handling code here:
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        
        
        
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton5ActionPerformed

    private class MySelectionListener implements ListSelectionListener {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            // TODO Auto-generated method stub
            try {
                String idOfBook = (String) model.getValueAt(
                        resultTable.getSelectedRow(), 0);
                try {
                    currentBook = client.getBookInfo(Integer.valueOf(idOfBook));
                } catch (SQLException ex) {
                    Logger.getLogger(BooksManagementsPane.class.getName()).log(Level.SEVERE, null, ex);
                }


                departmentNameField.setText(currentBook.getNameOfDepartment());
                caseNumberField.setText(currentBook.getBookCaseNumber());

                editionField.setText(currentBook.getNameOfEdition());
                dateField.setText(currentBook.getDateOfEdition());
                isbnField.setText(currentBook.getIsbn());
                titleField.setText(currentBook.getTitle());

                //positionFormatedField.setText(currentBook.getPositionOnBookCase());
                //fthis.authorsListModel.toArray();
                authorsListModel.clear();
                for (Author author : currentBook.getAuthors()) {
                    authorsListModel.addElement(author);
                }
                resultLabel.setText("selected");

            } catch (ArrayIndexOutOfBoundsException e1) {
                resultLabel.setText("nie wybrano działu");
                /*
                 * idOfDepartment = null; nameOfEditionHouse = ""; isbn = null;
                 */
            }
        }
    }
    private LibrarianUserClient client;
    private Book currentBook = new Book();
    private ArrayList<Author> authors = new ArrayList<Author>();
    private DefaultListModel authorsListModel = null;
    private EditionBook currentEdition = null;
    private Department currentDepartment = null;
    private DefaultTableModel model = null;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList authorsList;
    private javax.swing.JTextField caseNumberField;
    private javax.swing.JButton choseEditionButton;
    private javax.swing.JFormattedTextField dateField;
    private javax.swing.JTextField departmentNameField;
    private javax.swing.JTextField editionField;
    private javax.swing.JLabel idOfBook;
    private javax.swing.JFormattedTextField isbnField;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSpinner position;
    private javax.swing.JLabel resultLabel;
    private javax.swing.JTable resultTable;
    private javax.swing.JButton searchButton;
    private javax.swing.JTextField titleField;
    // End of variables declaration//GEN-END:variables
}
